import { useMemo, useState, useRef, useEffect } from "react";
import styles from "./index.module.less";
import { getTableColumns, getSearchColumns, getCreateColumns } from "./constant";
import { Modal, message, Button, Dropdown, Menu } from "antd";
import SuperTable from "@/components/SuperTable";
import cs from "classnames";
import { getUserList, createUser, getOrgTreeList, updateUser, deleteUser, getAllRole, resetPassword } from "@/api/modules/system";
import { RESULT_CODES } from "@/api/helper/ResultCode";
import useUrl from "@/hooks/useUrl";
import { cloneDeep, omit } from "lodash";
import RoleList from "./components/RoleList";
import SearchBox from "@/components/SearchBox";
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import CreateForm from "@/components/CreateForm";
import { EllipsisOutlined } from '@ant-design/icons';
import { getAllOrgList } from "@/api/modules/dict";
import { useRequest } from "ahooks";

export default () => {
	const { navigate } = useUrl();
	const [params, setParams] = useState({});
	const [orgTree, setOrgTree] = useState([]);
	const [defaultValues, setDefaultValues] = useState(null);
	const createFormRef = useRef(null);
	const dataTableRef = useRef();
	const { data: orgList } = useRequest(() => getAllOrgList({ page: { pageNum: 1, pageSize: 100 }}));
	const { data: roleList } = useRequest(() => getAllRole({}));

	const handleRequest = async (params: any) => {
		const paramsCopy = cloneDeep(params);
		const newParams = omit(paramsCopy, ['pageSize', 'current'])
		const requestData: any = {
			page: {
				pageSize: params.pageSize,
				pageNum: params.current
			},
			...newParams
		};

		const res = await getUserList(requestData);
		return {
			total: res?.data?.total ?? 0,
			data: res?.data?.list ?? []
		};
	};

	const handleResetPassword = (record: any) => {
		resetPassword({id: record.id}).then((res: any) => {
			if(res.code === 200) {
				message.success("密码重置成功~");
				dataTableRef?.current?.reload();
			}
		})
	}

	useEffect(() => {
		getOrgTreeList({}).then(res => {
			setOrgTree(res.data)
		})
	}, [])

	const edit = {
			label: "编辑",
			value: "edit"
		},
		deleteEnum = {
			label: "删除",
			value: "delete"
		},
		roleEnum = {
			label: "配置角色",
			value: "role"
		},
		passwordEnum = {
			label: "重置密码",
			value: "password"
		};

	const newColumns = [
		...getTableColumns({ params  }),
		{
			title: "操作",
			width: 200,
			fixed: "right",
			dataIndex: "action-render",
			options: (record: any) => {
				return [edit, deleteEnum, roleEnum, passwordEnum];
			},
			render: (key: string, record: any) => [
				<div key="edit" className={styles.tableBtn} onClick={() => handleEdit(record)}>编辑</div>,
				<div key="delete" className={styles.tableBtn} onClick={() => handleDelete(record)}>删除</div>,
				<div key="reset" className={cs(styles.tableBtn, styles.lastOne)} onClick={() => handleResetPassword(record)}>重置密码</div>
			]
		}
	];

	const handleEdit = (record: any) => {
		setDefaultValues(record);
		createFormRef?.current?.showModel();
	}

	const handleDelete = (record: any) => {
		Modal.confirm({
			icon: null,
			title: "删除提示？",
			content: `确认删除${record?.username}吗？`,
			closable: true,
			onOk: c => {
				deleteUser({ id: record?.id }).then((res: any) => {
					if (res?.code === RESULT_CODES.SUCCESS) {
						message.success("删除成功");
						c?.();
						dataTableRef?.current?.reload();
					}
				});
			}
		});
	}

	const NEW_SEARCH_COLUMNS = useMemo(() => {
		return getSearchColumns({orgList, roleList});
	}, [orgList, roleList]);
	
	const CREATE_COLUMNS = useMemo(() => {
		return getCreateColumns({orgList, roleList, defaultValues});
	}, [orgList, roleList, defaultValues]);

	const handleShowCreateModel = () => {
		setDefaultValues(null);
		createFormRef?.current?.showModel();
	}

	const handleCreate = (formData: any) => {
		const requestData = {
			...formData
		}
		if(defaultValues) {
			delete requestData.password
			updateUser({...requestData, id: defaultValues?.id}).then((res: any) => {
				if(res.code === 200) {
					message.success("用户更新成功~");
					createFormRef?.current?.closeModel();
					dataTableRef?.current?.reload();
					// 清空defaultValues，避免下次新增时回显编辑数据
					setDefaultValues(null);
				}
			})
		} else {
			createUser(formData).then((res: any) => {
				if(res.code === 200) {
					message.success("用户创建成功~");
					createFormRef?.current?.closeModel();
					dataTableRef?.current?.reload();
					// 清空defaultValues，确保状态一致
					setDefaultValues(null);
				}
			})
		}
	}

	const handleChooseOrg = (keys:any , info: any) => {
		// console.log(keys, info, '<============keys, info')
		setParams({
			...params,
			orgId: keys?.[0]
		});
	}

	const handleSearch = (e: any) => {
		setParams(e);
	};

	return (
		<div className={styles.flexContainer}>
			<CreateForm 
				title={defaultValues ? "编辑用户" : "创建用户"} 
				columns={CREATE_COLUMNS} 
				onCreate={handleCreate} 
				ref={createFormRef} 
				defaultValues={defaultValues}
			>
				<></>
			</CreateForm>
			<RoleList orgTree={orgTree} onChooseOrg={handleChooseOrg}/>
			<div className={styles.rightModule}>
				<SearchBox columns={NEW_SEARCH_COLUMNS} onSearch={handleSearch} >
					<div></div>
				</SearchBox>
				<div
					className={cs({
						[styles.container]: true
					})}
				>
					<div className={styles.operation_group}>
						<Button icon={<PlusOutlined /> } type="primary" onClick={handleShowCreateModel}>新增</Button>
						{/* <Button icon={<DeleteOutlined />} type="default">删除</Button> */}
					</div>
					<SuperTable
						params={{
							...params,
						}}
						ref={dataTableRef}
						// bordered
						rowKey="id"
						columns={newColumns}
						request={handleRequest}
						scroll={{ x: "900" }}
					/>
				</div>
			</div>

		</div>
	);
};
